import json
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .models import *
from django.contrib.auth.hashers import make_password
from django.contrib.auth.hashers import check_password
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
def home(request):
    return render(request, 'farmapp/index.html')


def register(request):
    if request.method == 'POST':
        # 获取注册表单数据
        username = request.POST.get("username")
        password = request.POST.get("password")
        password_confirm = request.POST.get("password_confirm")  # 获取确认密码
        email = request.POST.get("email")
        role = request.POST.get("role")

        # 验证用户名是否已存在
        if User.objects.filter(username=username).exists():
            messages.error(request, '用户名已被注册，请选择其他用户名。')
            return render(request, 'farmapp/register.html')

        # 验证密码和确认密码是否一致
        if password != password_confirm:
            messages.error(request, '两次输入的密码不一致，请重新输入。')
            return render(request, 'farmapp/register.html')

        # 密码加密
        hashed_password = make_password(password)

        # 创建新用户并保存
        user = User(username=username, password=hashed_password, email=email, role=role)
        user.save()

        # 根据角色创建个人资料
        if role == 'planter':
            Planter.objects.create(user=user)
        elif role == 'inspector':
            Inspector.objects.create(user=user)

        # 注册成功后提示并重定向到登录页面
        messages.success(request, '注册成功！')
        return render(request, 'farmapp/login.html')  # 假设你的登录视图名是 'login'

    else:
        return render(request, 'farmapp/register.html')


def login_view(request):
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")

        try:
            # 查找用户名对应的用户
            user = User.objects.get(username=username)

            # 验证密码
            if check_password(password, user.password):
                # 密码正确，登录用户
                login(request, user)

                # 根据角色跳转到不同的页面
                if user.role == 'admin':
                    return render(request, 'farmapp/admin_dashboard.html')
                elif user.role == 'planter':
                    return render(request, 'farmapp/planter_dashboard.html')
                elif user.role == 'inspector':
                    return render(request, 'farmapp/inspector_dashboard.html')
            else:
                messages.error(request, '密码错误，请重新输入')
        except User.DoesNotExist:
            messages.error(request, '用户名不存在，请注册一个新账户')

    return render(request, 'farmapp/login.html')

def admin_dashboard(request):
    return render(request, 'farmapp/admin_dashboard.html')

# def planter_dashboard(request):
#     return render(request, 'farmapp/planter_dashboard.html')

def inspector_dashboard(request):
    Inspector = Inspector.objects.get(user=request.user)
    return render(request, 'farmapp/inspector_dashboard.html')


def planter_dashboard(request):
    # 获取当前用户的种植员资料
    planter = Planter.objects.get(user=request.user)
    crops = Crop.objects.filter(planter=planter)  # 获取种植员的所有作物
    return render(request, 'farmapp/planter_dashboard.html', {'crops': crops})


def crop_list(request):
    planter = Planter.objects.get(user=request.user)
    crops = Crop.objects.filter(planter=planter)
    
    if request.method == 'POST':
        # 删除作物
        if 'delete_crop' in request.POST:
            crop_id = request.POST.get('crop_id')
            crop = get_object_or_404(Crop, id=crop_id)
            crop.delete()
            messages.success(request, '作物删除成功！')
            return render(request, 'farmapp/crop_list.html')
        
        # 编辑作物
        elif 'edit_crop' in request.POST:
            crop_id = request.POST.get('crop_id')
            crop = get_object_or_404(Crop, id=crop_id)
            crop.name = request.POST.get('name')
            crop.save()
            messages.success(request, '作物更新成功！')
            return render(request, 'farmapp/crop_list.html')

    return render(request, 'farmapp/crop_list.html', {'crops': crops})


def add_crop(request):
    if request.method == 'POST':
        # 获取表单数据并保存作物
        name = request.POST.get('name')
        crop_type = request.POST.get('crop_type')
        planting_date = request.POST.get('planting_date')
        location = request.POST.get('location')

        # 创建新的作物对象并关联到当前种植员
        crop = Crop(
            name=name,
            crop_type=crop_type,
            planting_date=planting_date,
            location=location,
            planter=Planter.objects.get(user=request.user)
        )
        crop.save()

        messages.success(request, '作物添加成功！')
        return render(request, 'farmapp/crop_list.html')  # 返回作物列表页面
    return render(request, 'farmapp/add_crop.html')



def log_list(request, crop_id):
    crop = get_object_or_404(Crop, id=crop_id)
    logs = crop.logs.all()
    
    if request.method == 'POST':
        # 删除日志
        if 'delete_log' in request.POST:
            log_id = request.POST.get('log_id')
            log = get_object_or_404(Log, id=log_id)
            log.delete()
            messages.success(request, '日志删除成功！')
            return render(request, 'farmapp/log_list.html')
        
        # 编辑日志
        elif 'edit_log' in request.POST:
            log_id = request.POST.get('log_id')
            log = get_object_or_404(Log, id=log_id)
            log.planting_date = request.POST.get('planting_date')
            log.quantity = request.POST.get('quantity')
            log.location = request.POST.get('location')
            log.save()
            messages.success(request, '日志更新成功！')
            return render(request, 'farmapp/log_list.html')

    return render(request, 'farmapp/log_list.html', {'crop': crop, 'logs': logs})


def add_log(request, crop_id):
    crop = get_object_or_404(Crop, id=crop_id)  # 获取相关作物
    if request.method == 'POST':
        # 获取表单数据并保存日志
        planting_date = request.POST.get('planting_date')
        quantity = request.POST.get('quantity')
        location = request.POST.get('location')

        # 创建新的日志对象并关联到对应作物
        log = Log(
            planting_date=planting_date,
            quantity=quantity,
            location=location,
            crop=crop
        )
        log.save()
        
        messages.success(request, '日志添加成功！')
        return render(request, 'farmapp/log_list.html')  # 返回日志列表页面
    return render(request, 'farmapp/add_log.html', {'crop': crop})


# 获取作物信息
def get_crops(request):
    crops = Crop.objects.filter(planter__user=request.user).values(
        'id', 'name', 'crop_type', 'planting_date', 'location'
    )
    return JsonResponse({'data': list(crops)})

def get_crop(request, id):
    """
    返回指定作物信息
    """
    try:
        crop = Crop.objects.filter(id=id, planter__user=request.user).values(
            'id', 'name', 'crop_type', 'planting_date', 'location'
        ).first()
        if crop:
            return JsonResponse(crop)
        return JsonResponse({'error': 'Crop not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

# 添加作物
@csrf_exempt
def add_crop(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        planter = Planter.objects.get(user=request.user)  # 获取当前登录的种植员
        Crop.objects.create(
            name=data['name'],
            crop_type=data['crop_type'],
            planting_date=data['planting_date'],
            location=data['location'],
            planter=planter
        )
        return JsonResponse({'message': '作物添加成功'})

# 编辑作物
@csrf_exempt
def update_crop(request, id):
    if request.method == 'PUT':
        data = json.loads(request.body)
        crop = get_object_or_404(Crop, id=id, planter__user=request.user)  # 确保种植员只能编辑自己的作物
        crop.name = data['name']
        crop.crop_type = data['crop_type']
        crop.planting_date = data['planting_date']
        crop.location = data['location']
        crop.save()
        return JsonResponse({'message': '作物更新成功'})

# 删除作物
@csrf_exempt
def delete_crop(request, id):
    if request.method == 'DELETE':
        crop = get_object_or_404(Crop, id=id, planter__user=request.user)
        crop.delete()
        return JsonResponse({'message': '作物删除成功'})

# 获取日志信息
def get_logs(request):
    logs = Log.objects.filter(crop__planter__user=request.user).values(
        'id', 'planting_date', 'quantity', 'location', 'crop__name'
    )
    return JsonResponse({'data': list(logs)})

def get_log(request, id):
    """
    返回指定日志信息
    """
    try:
        log = Log.objects.filter(id=id, crop__planter__user=request.user).values(
            'id', 'planting_date', 'quantity', 'location', 'crop__name'
        ).first()
        if log:
            return JsonResponse(log)
        return JsonResponse({'error': 'Log not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


# 添加日志
@csrf_exempt
def add_log(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        crop = get_object_or_404(Crop, id=data['crop'], planter__user=request.user)  # 确保作物属于当前种植员
        Log.objects.create(
            planting_date=data['planting_date'],
            quantity=data['quantity'],
            location=data['location'],
            crop=crop
        )
        return JsonResponse({'message': '日志添加成功'})

# 编辑日志
@csrf_exempt
def update_log(request, id):
    if request.method == 'PUT':
        data = json.loads(request.body)
        log = get_object_or_404(Log, id=id, crop__planter__user=request.user)
        log.planting_date = data['planting_date']
        log.quantity = data['quantity']
        log.location = data['location']
        log.save()
        return JsonResponse({'message': '日志更新成功'})

# 删除日志
@csrf_exempt
def delete_log(request, id):
    if request.method == 'DELETE':
        log = get_object_or_404(Log, id=id, crop__planter__user=request.user)
        log.delete()
        return JsonResponse({'message': '日志删除成功'})
    





def get_pests(request):
    pests = Pest.objects.all().values('id', 'pest_type', 'cause', 'solution')
    return JsonResponse({'data': list(pests)})

def get_pest(request, id):
    """
    返回指定害虫信息
    """
    try:
        pest = Pest.objects.filter(id=id).values('id', 'pest_type', 'cause', 'solution').first()
        if pest:
            return JsonResponse(pest)
        return JsonResponse({'error': 'Pest not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
    
@csrf_exempt
def add_pest(request):
    data = json.loads(request.body)
    Pest.objects.create(
        pest_type=data['pest_type'],
        cause=data['cause'],
        solution=data['solution']
    )
    return JsonResponse({'message': 'Pest added successfully'})
    
@csrf_exempt
def update_pest(request, id):
    """
    更新指定害虫信息
    """
    try:
        data = json.loads(request.body)
        pest = Pest.objects.get(id=id)
        pest.pest_type = data['pest_type']
        pest.cause = data['cause']
        pest.solution = data['solution']
        pest.save()
        return JsonResponse({'message': 'Pest updated successfully'})
    except Pest.DoesNotExist:
        return JsonResponse({'error': 'Pest not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@csrf_exempt
def delete_pest(request, id):
    """
    删除指定害虫信息
    """
    try:
        pest = Pest.objects.get(id=id)
        pest.delete()
        return JsonResponse({'message': 'Pest deleted successfully'})
    except Pest.DoesNotExist:
        return JsonResponse({'error': 'Pest not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


def get_inspections(request):
    inspections = InspectionRecord.objects.all().values(
        'id', 'inspection_date', 'inspection_type', 'result', 
        'crop__name', 'inspector__user__username'
    )
    return JsonResponse({'data': list(inspections)})

def get_inspection(request, id):
    """
    返回指定检测记录
    """
    try:
        inspection = InspectionRecord.objects.filter(id=id).values(
            'id', 'inspection_date', 'inspection_type', 'result',
            'crop_id', 'inspector_id'
        ).first()
        if inspection:
            return JsonResponse(inspection)
        return JsonResponse({'error': 'Inspection record not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
@csrf_exempt
def update_inspection(request, id):
    """
    更新指定检测记录
    """
    try:
        data = json.loads(request.body)
        inspection = InspectionRecord.objects.get(id=id)
        inspection.inspection_date = data['inspection_date']
        inspection.inspection_type = data['inspection_type']
        inspection.result = data['result']
        inspection.crop_id = data['crop']
        inspection.inspector_id = data['inspector']
        inspection.save()
        return JsonResponse({'message': 'Inspection record updated successfully'})
    except InspectionRecord.DoesNotExist:
        return JsonResponse({'error': 'Inspection record not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def delete_inspection(request, id):
    """
    删除指定检测记录
    """
    try:
        inspection = InspectionRecord.objects.get(id=id)
        inspection.delete()
        return JsonResponse({'message': 'Inspection record deleted successfully'})
    except InspectionRecord.DoesNotExist:
        return JsonResponse({'error': 'Inspection record not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)




@csrf_exempt
def add_inspection(request):
    data = json.loads(request.body)
    InspectionRecord.objects.create(
        inspection_date=data['inspection_date'],
        inspection_type=data['inspection_type'],
        result=data['result'],
        crop_id=data['crop'],
        inspector_id=data['inspector']
    )
    return JsonResponse({'message': 'Inspection record added successfully'})



# 获取单个用户
def get_user(request, id):
    try:
        user = User.objects.filter(id=id).values('id', 'username', 'email', 'role', 'last_login').first()
        if user:
            return JsonResponse(user)
        return JsonResponse({'error': 'User not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

# 添加用户
@csrf_exempt
def add_user(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        hashed_password = make_password(data['password'])
        user = User.objects.create(
            username=data['username'],
            email=data['email'],
            role=data['role'],
            password=hashed_password
        )
        return JsonResponse({'message': 'User added successfully', 'user_id': user.id})

# 编辑用户
@csrf_exempt
def update_user(request, id):
    if request.method == 'PUT':
        data = json.loads(request.body)
        user = get_object_or_404(User, id=id)
        user.username = data['username']
        user.email = data['email']
        user.role = data['role']
        user.password = make_password(data['password']) if 'password' in data else user.password
        user.save()
        return JsonResponse({'message': 'User updated successfully'})

# 删除用户
@csrf_exempt
def delete_user(request, id):
    if request.method == 'DELETE':
        user = get_object_or_404(User, id=id)
        user.delete()
        return JsonResponse({'message': 'User deleted successfully'})

# 获取所有用户信息
def get_users(request):
    users = User.objects.all().values('id', 'username', 'email', 'role', 'last_login')
    return JsonResponse({'data': list(users)})


# 获取种植员信息
def get_planters(request):
    planters = Planter.objects.all().values('id', 'user__username', 'contact_info')
    return JsonResponse({'data': list(planters)})

# 添加种植员
@csrf_exempt
def add_planter(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user = get_object_or_404(User, id=data['user_id'])
        Planter.objects.create(user=user, contact_info=data['contact_info'])
        return JsonResponse({'message': 'Planter added successfully'})

# 编辑种植员
@csrf_exempt
def update_planter(request, id):
    if request.method == 'PUT':
        data = json.loads(request.body)
        planter = get_object_or_404(Planter, id=id)
        planter.contact_info = data['contact_info']
        planter.save()
        return JsonResponse({'message': 'Planter updated successfully'})

# 删除种植员
@csrf_exempt
def delete_planter(request, id):
    if request.method == 'DELETE':
        planter = get_object_or_404(Planter, id=id)
        planter.delete()
        return JsonResponse({'message': 'Planter deleted successfully'})

# 获取检测员信息
def get_inspectors(request):
    inspectors = Inspector.objects.all().values('id', 'user__username', 'contact_info')
    return JsonResponse({'data': list(inspectors)})

# 添加检测员
@csrf_exempt
def add_inspector(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user = get_object_or_404(User, id=data['user_id'])
        Inspector.objects.create(user=user, contact_info=data['contact_info'])
        return JsonResponse({'message': 'Inspector added successfully'})

# 编辑检测员
@csrf_exempt
def update_inspector(request, id):
    if request.method == 'PUT':
        data = json.loads(request.body)
        inspector = get_object_or_404(Inspector, id=id)
        inspector.contact_info = data['contact_info']
        inspector.save()
        return JsonResponse({'message': 'Inspector updated successfully'})

# 删除检测员
@csrf_exempt
def delete_inspector(request, id):
    if request.method == 'DELETE':
        inspector = get_object_or_404(Inspector, id=id)
        inspector.delete()
        return JsonResponse({'message': 'Inspector deleted successfully'})